﻿using System;
using ReAnimation.DAL.Domain.Policies.Interfaces;
using ReAnimation.DAL.Domain.Policies.Interfaces.ErrorEnums;
using ReAnimation.Domain;
using ReAnimation.Helpers.Common;
using ReAnimation.Helpers.IoC;
using ReAnimation.Helpers.WinForms;
using ReAnimation.MVP.ModelInterfaces;
using ReAnimation.MVP.ViewInterfaces;

namespace ReAnimation.MVP.Presenters
{
    public class NewMoleculeDialogPresenter: BasePresenter<INewMoleculeDialogView>
    {
        private IMainModel _mainModel;
        private IMainPresentationModel _mainPresentationModel;
        private IMoleculePolicy _moleculePolicy;
        private ILazyInject<INotifier> _notifier;

        public NewMoleculeDialogPresenter(IMainModel mainModel, 
                                          IMainPresentationModel mainPresentationModel,
                                          IMoleculePolicy moleculePolicy,
                                          ILazyInject<INotifier> notifier)
        {
            _mainModel = mainModel;
            _mainPresentationModel = mainPresentationModel;
            _moleculePolicy = moleculePolicy;
            _notifier = notifier;
        }

        protected override void InitView()
        {
            _view.Create += ViewOnCreate;
            _view.ViewClose += ViewOnViewClose;
        }

        private void ViewOnViewClose(object sender, EventArgs eventArgs)
        {
            _view.Create -= ViewOnCreate;
            _view.ViewClose -= ViewOnViewClose;
        }

        private void ViewOnCreate(object sender, EventArg<string> eventArg)
        {
            ValidationResult<IncorrectMoleculeNameErrors> validationResult = _moleculePolicy.CheckName(eventArg.Data);
            if (!validationResult.IsError)
            {
                var molecule = new Molecule {Name = eventArg.Data};
                _mainModel.AddMolecule(molecule);
                _mainModel.CurrentMolecule = molecule;
                _view.Close();
            }
            else
            {
                //TODO: need an resource with the all strings for errors
                _notifier.Get().ShowMessage("Error",validationResult.Error.ToString());
            }
        }
    }
}
